import { Controller, Get, Json, Param, Post,
    Query, Body, Patch, Delete } from "@malagu/mvc/lib/node";
import { ResponseData } from "../../common";
import { Category } from "../entity";
import { jsonFormat } from '../utils';

@Controller("api/category")
export class CategoryController {
    @Get()
    async index(@Query("page") page: number = 1,
                @Query("size") size: number = 20):Promise<ResponseData<Category[]>> {
        let result = await Category.find({ 
          take: size,
          skip: size * (page - 1),
          order: { id: "DESC" }
        });
        return jsonFormat(result);
    }

    @Get(":id")
    async show(@Param("id" ) id: number): Promise<ResponseData<Category>> {
        let result = await Category.findOne({ id });
        return jsonFormat(result);
    }

    @Post()
    async create(@Body("json") postData: any): Promise<any> {
        let category = JSON.parse(postData);
        try {
            let saved = await Category.save(category);
            return jsonFormat(saved);
        }
        catch(e) {
            return jsonFormat(null, e);
        }
    }

    @Patch(":id")
    async update(@Param("id") id: number, @Body("json") postData: any): Promise<any> {
        let saveData = JSON.parse(postData);
        try {
            let saved = Category.update(id, saveData);
            return jsonFormat(saveData);
        }
        catch(e) {
            return jsonFormat(null, e);
        }
    }

    @Delete(":id")
    async delete(@Param("id") id: number): Promise<any> {
        try {
            let deleted = Category.delete({ id });
            return jsonFormat(deleted);
        }
        catch(e) {
            return jsonFormat(null, e);
        }
    }
}